package org.lex.swing.widgets.console.demo.windows;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;

import org.lex.swing.widgets.console.demo.ThreadPool;

public class WindowsCommandShell extends CommandShell {
	private PrintWriter shellWriter = null;
	private Reader shellStdOut = null;
	private Reader shellStdErr = null;
	private Writer stdOut = null;
	private Writer stdErr = null;

	protected WindowsCommandShell(Process shell, Writer stdOut, Writer stdErr) throws IOException {
		super(shell);
		this.stdOut = stdOut;
		this.stdErr = stdErr;
		this.shellStdOut = new InputStreamReader(shell.getInputStream());
		this.shellStdErr = new InputStreamReader(shell.getErrorStream());
		this.shellWriter = new PrintWriter(new OutputStreamWriter(shell.getOutputStream()));
	}

	public void execute(String command) throws IOException {
		System.out.println("cmd=" + command);
		if (false == command.endsWith("\r\n")) {
			command += "\r\n";
		}
		this.shellWriter.print(command);
		this.shellWriter.flush();
		this.readShellOutput();
	}

	private void readShellOutput() throws IOException {
		ThreadPool pool = ThreadPool.getInstance();
		pool.execute(new Runnable() {
			public void run() {
				try {
					read(shellStdOut, stdOut);
				} catch (IOException e) {
				}
			}
		});
		pool.execute(new Runnable() {
			public void run() {
				try {
					read(shellStdErr, stdErr);
				} catch (IOException e) {
				}
			}
		});
	}

	private String read(Reader in, Writer out) throws IOException {
		StringBuilder b = new StringBuilder();
		int len = 0;
		char[] buf = new char[256];
		try {
			while ((len = in.read(buf)) != -1) {
				b.append(buf, 0, len);
				out.write(buf, 0, len);
			}
		} catch (Exception e) {
		}
		return b.toString();
	}
}
